<!-- 打地鼠 -->
<template>
	<div class="molebox">
		<audio ref="music" :src="bgAudio" crossOrigin="anonymous" preload loop></audio>
		<audio ref="dzmusic" :src="dzAudio" crossOrigin="anonymous" preload></audio>
		<div v-if="operateType == 'result'">
			<div class="resultbox">
				<div class="imgbox">
					<div class="img-con" v-for="(item, index) in ranklist" @click="praiseStud(item)">
						<div class="imgItem" :class="['img0' + item.rank]">
							<img :src="(isPro ? '/impromptu_pro/img0' : '/impromptu/img0') + item.rank + '.png'" />
							<span class="number">{{ item.rank }}</span>
							<div class="name" :title="item.studName || ''">
								<div class="name-stuName" style="-webkit-box-orient: vertical">
									{{ item.studName || '' }}({{ item.score }}分)
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="rank">
					<div class="conbox-con">
						<div class="conbox-bd">
							<div class="list">
								<div class="item" v-for="(item, index) in allredpacklist" :key="index">
									{{ item.studName }}({{ item.score }}分)
								</div>
							</div>
						</div>
						<a href="javascript:;" class="closeWin" @click="reback"><img src="closeWin.png" alt="" /></a>
					</div>
				</div>
			</div>
		</div>
		<div class="stage" id="stage" v-if="operateType == 'answer' || operateType == 'nostart'">
			<div
				:id="'molespirit' + (index + 1)"
				class="molespirit"
				:class="['molespirit' + (index + 1)]"
				v-for="(item, index) in molelist"
				:key="index"
			>
				<div
					class="mole"
					:id="'mole' + (index + 1)"
					@animationend="(e) => onAnimationEnd(index)"
					:class="{ active: item.hasAni }"
				>
					<img :src="`/mole/mole${item.fit ? 2 : 1}.png`" alt="" />
					<div class="txt">
						{{ item.text }}
					</div>
				</div>
			</div>
		</div>
		<div class="fixed-save-btn" :class="{ over: isAnswering - 0 }" @click="startAnswer">
			{{ isAnswering - 0 ? '结束' : '开始' }}
		</div>
		<a href="javascript:;" v-if="operateType == 'nostart'" class="closeWin exit" @click="reback"
			><img src="closeWin.png" alt=""
		/></a>
	</div>
</template>

<script>
import $ from '@/utils/jquery-vendor';
import { generateRandomString, getBytesLength } from '@/utils/base';
function borad(info, score, stuName, profilePicture) {
	var time = new Date().getTime();
	$('.stage').append(
		"<div class='prizebox" +
			time +
			" prizebox' style='left:" +
			(parseInt(info.left) + 70) +
			'px;top:' +
			(parseInt(info.top) - 40) +
			"px;'><div class='num'><i></i><span>+" +
			score +
			"</span></div><div class='imgbox' " +
			(profilePicture ? "style='background-image: url(" + fileUrl + profilePicture + ")'" : '') +
			" ></div><div class='name'>" +
			stuName +
			'</div></div>'
	);
	$('.prizebox' + time).on('animationEnd webkitAnimationEnd', function () {
		$(this).remove();
	});
}
function getRandomNumber(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}
let timer = null;
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
export default {
	data() {
		return {
			bgAudio: '/mole/mp3/bg.mp3', //背景音乐
			dzAudio: '/mole/mp3/dazhong.wav',
			operateType: 'nostart',
			molelist: [
				{
					text: 'A',
					hasAni: false,
					num: 0,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 1,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 2,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 3,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 4,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 5,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 6,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 7,
					fit: 0,
				},
				{
					text: 'A',
					hasAni: false,
					num: 8,
					fit: 0,
				},
			],
			ranklist: [],
			allredpacklist: [],
		};
	},
	computed: {
		...mapState({
			deviceType: (state) => state.websockStore.deviceType,
			studentList: (state) => state.websockStore.studentList,
			isPro: (state) => state.isPro,
			stopDeviceEventList: (state) => state.websockStore.stopDeviceEventList,
			minProjectLogin: (state) => state.minProjectStore.minProjectLogin, //小程序是否登录
			isAnswering: (state) => state.websockStore.isAnswering,
		}),
		wiredAnswer() {
			return this.$store.getters.onEvent('wiredanswer');
		},
	},
	watch: {
		//有线设备上报答题数据
		wiredAnswer: {
			handler(newValue, oldValue) {
				if (newValue && newValue != oldValue) {
					let uID = newValue.uID - 0;
					let stuInfo = this.studentList.find((item) => item.machineId - 0 == uID);
					this.ans_id = sessionStorage.getItem('ans_id');
					if (this.ans_id && this.ans_id == newValue.ans_id) {
						let info = this.studentList.find((item) => item.machineId - 0 == uID);
						if (!!info) {
							this.checkMole(newValue.ans_str, info.studName, info.machineId);
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
	},

	mounted() {
		var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		var screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
		let scaleX = screenWidth / 807;
		let scaleY = (screenHeight - 120) / 581;
		let scale = scaleX > scaleY ? scaleY : scaleX;
		$('.stage').css({
			transform: 'translate(-50%,-50%) scale(' + scale + ', ' + scale + ')',
		});
		let moleId = this.$ls.get('moleId') || '';
		if (moleId && this.isAnswering - 0) {
			this.operateType = 'answer';
			timer = setInterval(() => {
				this.addAni();
			}, 1000);
			this.$nextTick(() => {
				this.$refs.music.play();
			});
		}
	},

	destroyed() {
		if (timer) {
			clearInterval(timer);
		}
	},
	methods: {
		...mapMutations(['WEBSOCKET_SEND', 'SET_isAnswering', 'SET_ANS_ID']),
		addAni() {
			let noAni = this.molelist.filter((item) => !item.hasAni).map((item) => item.num);
			if (noAni.length > 0) {
				let index = Math.floor(Math.random() * noAni.length);
				let moleIndex = noAni[index];
				let letter = ['A', 'B', 'C', 'D', '√', '×', 'OK'][Math.floor(Math.random() * 7)];
				this.molelist[moleIndex].hasAni = true;
				this.molelist[moleIndex].fit = 0;
				this.molelist[moleIndex].text = letter;
			}
		},
		checkMole(letter, studName, machineId) {
			letter = letter == 'E' ? '√' : letter == 'F' ? '×' : letter == 'G' ? 'OK' : letter;
			let list = this.molelist.filter((item) => !item.fit && item.text == letter);
			let objlist = [];
			list.forEach((item, index) => {
				var reg = /matrix.((.+([, ]+)?){6})./g;
				var str = $('#mole' + (item.num + 1)).css('transform');
				var arr = reg.exec(str);
				var newarr = arr[1].split(/[, ]+/g);
				var bottom = parseFloat(newarr[5]);
				console.log('bottom', bottom);
				if (bottom < 82 - 40) {
					/* 冒出地面40像素 ，则能够被打中*/
					objlist.push({
						...item,
					});
				}
			});
			if (objlist.length > 0) {
				this.$refs.dzmusic.play();
				let objindex = Math.floor(Math.random() * objlist.length);
				let info = objlist[objindex];
				let score = getRandomNumber(1, 10);
				borad(
					{
						left: $('#molespirit' + (info.num + 1)).css('left'),
						top: $('#molespirit' + (info.num + 1)).css('top'),
					},
					score,
					studName
				);
				this.molelist[info.num].fit = 1;
				let msg = '   ' + studName;
				let len = 16 - getBytesLength(msg);
				for (var i = 0; i < len; i++) {
					msg = msg + ' ';
				}
				msg = msg + '   获得' + score + '积分';
				this.WEBSOCKET_SEND({
					fun: 'dtq_echo_set',
					uID: machineId - 0,
					msg: msg,
				});
				let index = this.allredpacklist.findIndex((item) => item.machineId == machineId);
				if (index > -1) {
					this.allredpacklist[index].score = score + this.allredpacklist[index].score;
				} else {
					this.allredpacklist.push({
						...info,
						studName,
						machineId,
						score,
					});
				}
			}
		},
		onAnimationEnd(e) {
			this.molelist[e].hasAni = false;
			this.molelist[e].fit = 0;
		},
		//去答题
		startAnswer() {
			if (this.isAnswering - 0) {
				this.stopAnswer();
				return;
			}
			/* 判断移动端正在控制PC端 */
			/*if (this.minProjectLogin) {
				this.$message.error('移动端正在控制PC端，不能发题！');
				return;
			}*/
			//发题前判断该班级是否有学生。
			if (this.studentList.length == 0) {
				let tempTestData = this.$ls.get('tempTestData');
				this.$message.error('（' + tempTestData.className + '）班级没有学生，请先添加学生！');
				return;
			}
			this.molelist.forEach((item) => {
				item.hasAni = false;
				item.fit = 0;
			});
			this.allredpacklist = [];
			timer = setInterval(() => {
				this.addAni();
			}, 1000);
			this.$nextTick(() => {
				this.$refs.music.play();
			});
			this.sendStartAnswer();
		},
		sendStartAnswer() {
			this.$ls.set('moleId', generateRandomString());
			this.WEBSOCKET_SEND({
				fun: 'answer_start',
				uID: 0,
				type: 6,
				q_cnt: 10,
			});
			this.studentList.forEach((item) => {
				if (item.status == 1) {
					let msg = '   ' + item.studName;
					let len = 16 - getBytesLength(msg);
					for (var i = 0; i < len; i++) {
						msg = msg + ' ';
					}
					msg = msg + '请按任意键打地鼠';
					this.WEBSOCKET_SEND({
						fun: 'dtq_echo_set',
						uID: item.machineId - 0,
						msg: msg,
					});
				}
			});
			this.operateType = 'answer';
			this.SET_isAnswering(1);
		},
		stopAnswer() {
			this.WEBSOCKET_SEND({
				fun: 'answer_start',
				uID: 0,
				type: 128, //结束答题
			});
			this.operateType = 'result';
			this.SET_isAnswering(0);
			this.SET_ANS_ID('');
			this.$ls.remove('moleId');
			this.studentList.forEach((item) => {
				if (item.status == 1) {
					let msg = '   ' + item.studName;
					this.WEBSOCKET_SEND({
						fun: 'dtq_echo_set',
						uID: item.machineId - 0,
						msg: msg,
					});
				}
			});
			if (timer) {
				clearInterval(timer);
				timer = null;
			}
			if (this.$refs.music) {
				this.$refs.music.pause();
				this.$refs.music.currentTime = 0;
			}
			let allredpacklist = [...this.allredpacklist];
			allredpacklist.sort((a, b) => {
				return b.score - a.score;
			});
			this.allredpacklist = [...allredpacklist];
			let ranklist = this.allredpacklist.slice(0, 5);
			let rank = 1;
			ranklist.forEach((item, index) => {
				if (index > 0 && item.score < ranklist[index - 1].score) {
					rank = index + 1;
				}
				item.rank = rank;
			});
			this.ranklist = [...ranklist];
		},
		//返回
		reback() {
			this.$emit('checkMenu', { type: 'mole' });
		},
	},
};
</script>

<style scoped lang="less">
.molebox {
	background: url(/redpack/redpackbg.jpg) no-repeat center bottom;
	height: 100%;
	width: 100%;
	position: relative;
}
.stage {
	background: url(/mole/bg.png);
	background-size: contain;
	width: 807px;
	height: 581px;
	margin: 0 auto;
	position: absolute;
	top: 50%;
	// bottom: 80px;
	left: 50%;
	transform-origin: 50% 50%;
	transform: translate(-50%, -50%) scale(1.2, 1.2);
}
.molespirit {
	position: absolute;
	width: 60px;
	height: 83px;
	overflow: hidden;
	&.molespirit1 {
		top: 206px;
		left: 200px;
	}
	&.molespirit2 {
		top: 206px;
		left: 390px;
	}
	&.molespirit3 {
		top: 210px;
		left: 580px;
	}
	&.molespirit4 {
		top: 300px;
		left: 172px;
	}
	&.molespirit5 {
		top: 300px;
		left: 390px;
	}
	&.molespirit6 {
		top: 299px;
		left: 590px;
	}
	&.molespirit7 {
		top: 396px;
		left: 166px;
	}
	&.molespirit8 {
		top: 402px;
		left: 390px;
	}
	&.molespirit9 {
		top: 403px;
		left: 610px;
	}
}

.molespirit img {
	display: block;
	width: 100%;
}
.mole {
	position: relative;
	transform: translateY(100%);
	opacity: 0;
}
.mole.active {
	animation: mouse-move 3s ease-in-out 1 forwards;
}
.molespirit .txt {
	border: 2px solid #8c5153;
	background: #fff;
	width: 30px;
	height: 30px;
	border-radius: 100%;
	position: absolute;
	left: 50%;
	bottom: 1px;
	transform: translateX(-50%);
	text-align: center;
	line-height: 26px;
	color: #ba00ff;
	font-weight: 600;
	font-size: 20px;
}
.fixed-save-btn {
	background: @primary-color;
	width: 300px;
	height: 60px;
	line-height: 60px;
	border-radius: 40px;
	text-align: center;
	color: #fff;
	font-size: 30px;
	font-weight: bold;
	cursor: pointer;
	position: fixed;
	bottom: 20px;
	left: 50%;
	transform: translateX(-50%);
	z-index: 9;
	&.over {
		background: @warning-color;
	}
}
.closeWin {
	position: absolute;
	right: -20px;
	bottom: -16px;
	width: 46px;
	height: 46px;
	img {
		display: block;
		width: 100%;
		height: 100%;
	}
	&.exit {
		bottom: 22px;
		left: 50%;
		transform: translateX(300px);
	}
}

.conbox-con {
	height: 100%;
	border-radius: 8px;
	background: transparent;
	z-index: 6;
	position: relative;
}
.conbox-hd {
	font-size: 22px;
	color: #2e2424;
	text-align: center;
	position: relative;
	margin-bottom: 20px;
	margin-top: 0;
}

.conbox-bd {
	width: 1162px;
	height: calc(100vh - 400px);
	margin: 0 auto 27px;
	background: rgb(243, 248, 255);
	border: 2px solid @primary-color;
	border-radius: 10px;
	overflow: hidden;
	position: relative;

	.list {
		margin: 20px;
		background: rgb(255, 255, 255);
		border: 2px dashed @primary-color;
		border-radius: 10px;
		height: calc(100% - 40px);
		font-size: 20px;
		color: #2e2424;
		padding: 20px 62px 40px;
		overflow: auto;
		text-align: left;
		.item {
			width: 25%;
			display: inline-block;
			cursor: pointer;
			text-align: left;
			margin-bottom: 30px;
			.name {
				//margin-right: 18px;
				width: 5em;
				display: inline-block;
				text-align: left;
				word-break: break-all;
				vertical-align: middle;
				margin-right: 10px;
			}

			.number {
				display: inline-block;
				width: 12em;
				text-align: left;
				vertical-align: middle;
			}
		}
	}
}
.resultbox {
	/***排名***/
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	.rank {
		text-align: center;
		width: 1162px;
		margin: 250px auto 0;
		// padding: 50px 0 30px;
		@media screen and (max-width: 1366px) {
			width: 1024px;
		}
	}

	.imgbox {
		position: fixed;
		top: 80px;
		left: 50%;
		transform: translateX(-50%);
		// height: 199px;
		display: flex;

		.img-con {
			height: 157px;
			display: inline-block;
			position: relative;
			display: flex;
			align-items: flex-end;
			cursor: pointer;
		}

		.imgItem {
			position: absolute;
			bottom: 0;
			display: inline-block;
			margin: 0 20px;
			position: relative;
			text-align: center;

			img {
				width: 100%;
				height: 100%;
				/* position: absolute;
						bottom: 0; */
			}

			.number {
				position: absolute;
				top: 0;
				left: 50%;
				transform: translate(-50%);
				color: #fff;
				font-weight: bold;
			}

			.name {
				width: 100%;
				position: absolute;
				bottom: 11px;
				text-align: center !important;
				color: #fff;
				font-weight: bold;
				.name-stuName {
					padding: 0 0 7px;
					text-align: center !important;
					white-space: nowrap;
				}
			}

			&.img01 {
				//width: 231px;
				width: 181px;
				font-size: 26px;

				.number {
					top: 2%;
					font-size: 60px;
				}
				.name-stuName {
					line-height: 30px;
				}
			}

			&.img02 {
				//width: 198px;
				width: 148px;
				font-size: 24px;

				.number {
					top: 5%;
					font-size: 50px;
				}

				.name {
					bottom: 8px;
				}
				.name-stuName {
					line-height: 28px;
				}
			}

			&.img03 {
				//width: 178px;
				width: 128px;
				font-size: 22px;

				.number {
					top: 8%;
					font-size: 40px;
				}

				.name {
					bottom: 5px;
				}
				.name-stuName {
					line-height: 26px;
				}
			}

			&.img04 {
				//width: 131px;
				width: 110px;
				font-size: 18px;

				.number {
					top: 9%;
					font-size: 32px;
				}

				.name {
					bottom: 7px;
				}
				.name-stuName {
					line-height: 18px;
				}
			}

			&.img05 {
				width: 96px;
				//width: 66px;
				font-size: 16px;

				.number {
					font-size: 30px;
					top: 8%;
				}

				.name {
					bottom: 5px;
				}
				.name-stuName {
					line-height: 16px;
				}
			}
		}
		@media screen and (max-width: 1366px) {
			position: fixed;
			top: 40px;
			.imgItem {
				&.img01 {
					width: 141px;
					font-size: 26px;

					.number {
						top: 2%;
						font-size: 50px;
					}
					.name {
						bottom: 6px;
					}
				}

				&.img02 {
					//width: 198px;
					width: 148px;
					font-size: 24px;

					.number {
						top: 5%;
						font-size: 50px;
					}

					.name {
						bottom: 8px;
					}
				}

				&.img03 {
					//width: 178px;
					width: 128px;
					font-size: 22px;

					.number {
						top: 8%;
						font-size: 40px;
					}

					.name {
						bottom: 5px;
					}
				}

				&.img04 {
					//width: 131px;
					width: 110px;
					font-size: 14px;

					.number {
						top: 9%;
						font-size: 32px;
					}

					.name {
						bottom: 7px;
					}
				}

				&.img05 {
					width: 96px;
					//width: 66px;
					font-size: 12px;

					.number {
						font-size: 30px;
						top: 8%;
					}

					.name {
						bottom: 5px;
					}
				}
			}
		}
	}
}
</style>
<style lang="less">
.molebox {
	.prizebox {
		position: absolute;
		top: 50%;
		width: 200px;
		height: 190px;
		background: url(/redpack/avatar/redpackbg.png) no-repeat center center;
		background-size: 100% auto;
		padding-top: 40px;
		opacity: 0;
		animation: 2.5s 0s fadeOutUp;
		transform-origin: 50% 50%;
		-webkit-transform: scale3d(0.3, 0.3, 0.3) translate3d(-50%, 0, 0);
		transform: scale3d(0.3, 0.3, 0.3) translate3d(-50%, 0, 0);
	}
	.prizebox .imgbox {
		width: 90px;
		height: 90px;
		border-radius: 100%;
		overflow: hidden;
		margin: 0 auto;
		background: #fffcda url(/redpack/avatar/5.jpg) no-repeat center center;
		background-size: cover;
		position: absolute;
		top: 62px;
		transform: translateX(-50%);
		left: 50%;
	}

	.prizebox .name {
		position: absolute;
		bottom: 16px;
		padding-top: 8px;
		color: #fff;
		font-size: 16px;
		font-weight: bold;
		text-align: center;
		line-height: 20px;
		width: 120px;
		height: 41px;
		transform: translateX(-50%);
		left: 50%;
		text-shadow: 0 1px 0 rgba(126, 84, 1, 1);
		background: url(/redpack/avatar/namebg.png) no-repeat center center;
		background-size: cover;
	}
	.prizebox .num {
		color: #fff;
		background: #e52946;
		border: 2px solid #ffc812;
		border-radius: 50px;
		line-height: 28px;
		height: 32px;
		padding: 0 20px;
		top: 30px;
		left: 50%;
		font-size: 20px;
		transform: translateX(-50%);
		position: absolute;
		display: flex;
		align-items: center;
	}
	.prizebox .num i {
		display: block;
		height: 22px;
		width: 22px;
		vertical-align: -0.25em;
		background: url(/redpack/avatar/star2.png);
		background-size: cover;
	}
}

@keyframes mouse-move {
	0% {
		transform: translateY(100%);
		opacity: 0;
	}
	30% {
		transform: translateY(0);
		opacity: 1;
	}
	80% {
		transform: translateY(0);
		opacity: 1;
	}
	100% {
		transform: translateY(100%);
		opacity: 0;
	}
}
</style>
